<template>
  <Row >
    <!-- 讨论详情版块 -->  
    <!-- 讨论的内容部分 -->
    
    <div v-if="preparing === true">
      <el-card>
        <div style="font-size: 40px; font-weight: 800;">讲解视频正在努力准备中...</div>
      </el-card>
    </div>
    <div v-show="preparing === false">
      <el-row >
        <!-- 赞 和 收藏 -->
        <el-col style="width:4%;font-size: 30px;flex-direction:column;display: flex; align-items: center;" >
          
          <i v-if="t<2" @click="editLike(1)" class="el-icon-caret-top" style="font-size: 35px;"></i>
          <i v-if="t===2" @click="editLike(1)" class="el-icon-caret-top" style="color: orange;font-size: 35px;"></i>
          <div style="text-align: center;">{{discussion.like_number}}</div>
          <i v-if="t%2===0" @click="editLike(2)" class="el-icon-caret-bottom" style="font-size: 35px;"></i>
          <i v-if="t===1" @click="editLike(2)" class="el-icon-caret-bottom" style="color: orange;font-size: 35px;"></i>
          <i v-if="!star" @click="changeStar" class="el-icon-star-off"></i>
          <i v-if="star" @click="changeStar" class="el-icon-star-on" style="color:gold" ></i>
          <div v-if="discussion.star_number >0">{{discussion.star_number }}</div>
          
        </el-col >
        <el-col  style="width:96%;">
          <v-md-preview :text="discussion.discussion_text" @copy-code-success="handleCopyCodeSuccess"></v-md-preview>
          <!-- 讲解视频 -->
          <el-card style="margin:20px">
            <video  id="video-problem" width="1000" playsinline webkit-playsinline>
            </video>
          </el-card>

          <!-- 额外信息 -->
          <div style="margin-top: 10px;">
            <ul class="detail">
              <!-- 浏览数 -->
              <li> <i class="el-icon-view"></i> {{discussion.view_number }} </li>
              <!-- 回复数 -->
              <li> <i class="el-icon-chat-line-square"></i> {{discussion.reply_number }} </li> 
                <!-- 右对齐的部分，主要是用户信息 -->
              <li style="float: right">
                <!-- 如果是用户自己的讨论，他可以编辑 -->
                <a v-show="discussion.created_by.id === user.id"
                  @click="editDiscussion()">
                  <i class="el-icon-edit"></i> 
                  {{$t('m.Edit')}}
                </a> &nbsp;&nbsp;&nbsp;
                <!-- 最后编辑时间 -->
                <a>{{discussion.created_by.username}}</a>
                编辑于
                {{discussion.last_edit_time | localtime('YYYY-M-D HH:mm') }}
                <!-- 编辑者，todo: 跳转到编辑者的个人界面，可以显示用户的所有讨论和回复 -->
              </li>
            </ul>
          </div>
        </el-col >
      </el-row>


      <el-col style="margin-top: 30px; padding: 20px" >
        <div style="font-size: 30px;font-weight: 800;margin: 30px 0;">评论</div>
        <div style="padding: 0 30px " >
          <el-input
            type="textarea"
            placeholder="请输入评论,支持Latex 和 markdown 语法"
            v-model="discussionReply.reply_text"
            maxlength="2000"
            maxline="20"
            :autosize="{ minRows: 4, maxRows: 35 }"
            show-word-limit        
          >
          </el-input>
          <div style="text-align: right; ">
            <el-button type="text" style="font-size:18px" @click="finishCreateDiscussionReply" >提交评论</el-button>
          </div>
        </div>

        <el-divider></el-divider>
        
        <p v-if="discussion.reply_number === 0" id="no-reply">{{$t('m.No_Reply')}}</p>
        <reply-tree-node :replies="replies" :open="true" :closed="discussion.closed"
                        :open_next="open_next" :init="init"></reply-tree-node>
        <Pagination :total="total" :pageSize="limit" @on-change="getReply" :current.sync="page"></Pagination>
      </el-col>
    </div>
  </Row>

</template>

<script>
import api from '@oj/api'
import { mapGetters } from 'vuex'
import utils from '@/utils/utils'
import { USER_TYPE } from '@/utils/constants'
import Pagination from '@/pages/oj/components/Pagination'
import Simditor from '@admin/components/Simditor.vue'
import ReplyTreeNode from '@/pages/oj/components/ReplyTreeNode'
import time from '@/utils/time'
const limit = 10
export default {
  name: 'ProblemVideo',
  components: {
    Pagination,
    Simditor,
    ReplyTreeNode
  },
  props: {
    fileID: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      page: 1,
      query: {
        fileID: ''
      },
      limit: limit,
      total: 0,
      rows: '',
      title: this.$i18n.t('m.All_Discussion'),
      discussion: {
        created_by: {
          id: null
        }
      },
      replies: [],
      open_next: [],
      reply_text: '',
      discussionReply: {},
      discussion_type: '',
      star: false,
      t: 0,
      nt: 0,
      like_id: 0,
      TCPlayer: null,
      preparing: null,
      options: {
        fileID: '',
        appID: '1306498106',
        psign: '',
        plugins: {
          ProgressMarker: true,
          ContextMenu: {
            levelSwitch: {
              open: true,
              switchingText: '开始切换清晰度 ',
              switchedText: '切换成功',
              switchErrorText: '切换失败'
            }
          },
          ContinuePlay: { // 开启续播功能
            auto: true,
            text: '上次播放至 ',
            btnText: '恢复播放'
          },
          DynamicWatermark: {
            speed: 0.2,
            content: ''
          }
        },
        autoplay: false,
        language: 'zh-CN'
      }
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    addViewCount () {
      api.addViewCount(this.fileID).then(res => {
        // 不知道为啥时灵时不灵。。
        this.discussion.view_number += 1
      })
    },
    init () {
      let route = this.$route.query
      this.TCPlayer = null
      this.query.discussion_id = this.fileID
      this.page = parseInt(route.page) || 1
      this.getDiscussion()
    },
    getReply (page = 1) {
      let offset = (page - 1) * this.limit
      api.getReplyList(offset, this.limit, this.query).then((res) => {
        this.replies = res.data.data.results
        this.total = res.data.data.total
        this.open_next = res.data.data.open_next
      })
    },
    getStarStatus () {
      let query = {}
      query.type = 'discussion'
      query.id = this.fileID
      api.starExists(query).then(res => {
        // console.log(res)
        this.star = res.data.data
      })
    },
    getLike () {
      api.getLike({id: this.fileID}).then(res => {
        console.log(res.data.data)
        if (res.data.data !== -1) {
          this.t = res.data.data.num
          this.like_id = res.data.data.id
        } else {
          api.createLike({discussion_id: this.fileID, num: 0}).then(res => {
            this.t = 0
            this.like_id = res.data.data.id
          })
        }
      })
    },
    editLike (w) {
      if (w === 1) {
        if (this.t === 1) {
          this.nt = 2
        } else {
          this.nt = this.t ^ 2
        }
      } else {
        if (this.t === 2) {
          this.nt = 1
        } else {
          this.nt = this.t ^ 1
        }
      }
      let like = {}
      like.id = this.like_id
      like.num = this.nt
      like.change = -(this.nt % 2) + (this.nt > 1) + (this.t % 2) - (this.t > 1)
      api.editLike(like).then(res => {
        this.t = this.nt
        this.discussion.like_number += like.change
      })
    },
    changeStar () {
      if (!this.star) {
        let par = {}
        par.discussion_id = this.fileID
        api.createStar(par).then(res => {
          this.star = !this.star
        })
      } else {
        let par = {}
        par.star_id = this.fileID
        par.type = 'discussion'
        api.deleteStar(par).then(res => {
          this.star = !this.star
        })
      }
    },
    getDiscussion () {
      this.discussionReply.reply_to = this.fileID
      if (this.fileID === 0) {
        this.preparing = true
        return
      }
      this.discussionReply.reply_to_discussion = true
      api.getDiscussion(this.fileID).then(res => {
        this.discussion = res.data.data
        var videoUrl = res.data.data.discussion_title
        api['getSign'](videoUrl).then((res) => {
          this.preparing = false
          this.options.fileID = res.data.data.fileID
          this.options.psign = res.data.data.psign
          this.options.plugins.DynamicWatermark.content = this.user.id.toString()
          if (this.TCPlayer === null) {
            this.TCPlayer = window.TCPlayer('video-problem', this.options)
          } else {
            this.TCPlayer.loadVideoByID(this.options)
          }
        }).catch()
        this.getReply()
        this.addViewCount()
        if (this.user.id) {
          this.getStarStatus()
          this.getLike()
        }
      })
    },
    changeRoute () {
      let query = Object.assign({}, this.query)
      query.page = this.page
      this.$router.push({
        name: 'discussion-list',
        query: utils.filterEmptyValue(query)
      })
    },
    editDiscussion () {
      if (this.discussion.problem) {
        this.$router.push({name: 'discussion-edit', params: {fileID: this.discussion.id, problem_id: this.discussion.problem._id}})
      } else {
        this.$router.push({name: 'discussion-edit', params: {fileID: this.discussion.id}})
      }
    },
    finishCreateDiscussionReply () {
      if (!this.discussionReply.reply_text) { return }
      api['createReply'](this.discussionReply).then(res => {
        this.init()
        this.discussionReply.reply_text = ''
      }).catch()
    },
    getDuration (startTime, endTime) {
      return time.duration(startTime, endTime)
    },
    handleCopyCodeSuccess () {
      this.$notify({
        title: '复制成功',
        type: 'success',
        duration: 2000
      })
    }
  },
  computed: {
    ...mapGetters(['user', 'theme']),
    isAdmin () {
      return this.user.admin_type === USER_TYPE.SUPER_ADMIN
    }
  },
  watch: {
    '$route' (newVal, oldVal) {
      if (newVal !== oldVal) {
        this.init()
      }
    }
  },
  beforeDestroy () {
    this.TCPlayer.dispose()
    this.TCPlayer = null
  },
  beforeCreate () {
    this.TCPlayer = null
  }
}
</script>

<style scoped>
.detail > li{
  margin-left: 20px;
  display: inline-block;
  font-size: 16px;
}
.content-container {
  padding: 0 20px 20px 20px;
}
.top {
  padding: 10px;
  width: 45px;
  background: rgba(0, 0, 0, .5);
  color: #fff;
  text-align: center;
  border-radius: 2px;
}
#no-reply {
  text-align: center;
font-size: 16px;
  padding: 20px;
}
</style>